//
//  PayTheVIPViewController.m
//  MagazineShangejie
//
//  Created by wen on 15/10/29.
//  Copyright © 2015年 CnbizMedia. All rights reserved.
//

#import "PayTheVIPViewController.h"
#import "Util.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WXApiObject.h"
//APP端签名相关头文件 微信
#import "payRequsestHandler.h"
#import "PayOkViewController.h"
#import "PayBadViewController.h"
@interface PayTheVIPViewController (){

    NSDictionary *orderDic;
    NSDictionary *goodsPayData;
}
@property (weak, nonatomic) IBOutlet UIButton *wxPayButton;
@property (weak, nonatomic) IBOutlet UIButton *zfbPayButton;

@property (weak, nonatomic) IBOutlet UILabel *theNumber;
@property (weak, nonatomic) IBOutlet UILabel *vipName;
@property (weak, nonatomic) IBOutlet UILabel *theTime;
@property (weak, nonatomic) IBOutlet UILabel *vipMoney;
@property (weak, nonatomic) IBOutlet UILabel *userName;
@end

@implementation PayTheVIPViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    
//    _wxPayButton.imageView.image = [UIImage imageNamed:@"payYes"];
//    _zfbPayButton.imageView.image = [UIImage imageNamed:@"payWhi"];
//    [_wxPayButton setBackgroundImage:[UIImage imageNamed:@"payYes"] forState:UIControlStateNormal];
    
    [_wxPayButton setBackgroundImage:[UIImage imageNamed:@"payYes"] forState:UIControlStateSelected];
    
    [_wxPayButton setBackgroundImage:[UIImage imageNamed:@"payWhi"] forState:UIControlStateNormal];
    
    
    [_zfbPayButton setBackgroundImage:[UIImage imageNamed:@"payYes"] forState:UIControlStateSelected];
    
    [_zfbPayButton setBackgroundImage:[UIImage imageNamed:@"payWhi"] forState:UIControlStateNormal];

    _wxPayButton.selected=YES;
    
    _zfbPayButton.selected=NO;
    
    if ([[UserDefaults objectForKey:@"VIP"] isEqualToString:@"VIP"]) {
         _vipName.text = @"铂金用户";
        _vipMoney.text = @"￥6000.00";
    }
    else{
        _vipName.text = @"钻石用户";
        _vipMoney.text = @"￥20000.00";
    }
    
    goodsPayData =  [UserDefaults objectForKey:@"goodsPayData"];
    _vipName.text = goodsPayData[@"content"];
    _vipMoney.text = [NSString stringWithFormat:@"￥%@" ,goodsPayData[@"total"] ];
    
    orderDic = [[NSDictionary alloc] init];
    
    NSString *vipName    = @"购买VIP";
//    if ([[UserDefaults objectForKey:@"VIP"] isEqualToString:@"VIP"]) {
//        vipName = @"铂金用户";
//        orderDic = [UserDefaults objectForKey:@"Goodaaaccc"];
//        //        _vipMoney.text = @"￥6000.00";
//    }
//    else{
//        vipName = @"钻石用户";
//        orderDic = [UserDefaults objectForKey:@"Diamondaaaccc"];
//        //        _vipMoney.text = @"￥20000.00";
//    }
    _theNumber.text = [goodsPayData objectForKey:@"order_sn"];
 
    
    //接收通知的设置,接收成功微信支付后返回上一个界面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popOfDismss) name:@"getBackToUpView" object:nil];//都是nil

    UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;
    
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm"];
    NSString *date =  [formatter stringFromDate:[NSDate date]];
    NSString *timeLocal = [[NSString alloc] initWithFormat:@"%@", date];
    
    NSLog(@"[orderDic objectForKey:  = %@",[goodsPayData objectForKey:@"addtime"]);
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[[goodsPayData objectForKey:@"addtime"] integerValue]];
    NSLog(@"1296035591  = %@",confromTimesp);
    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
    NSLog(@"confromTimespStr =  %@",confromTimespStr);
    
    _theTime.text = confromTimespStr;
    NSLog(@"%@", timeLocal);
    
    
    _userName.text=[NSString stringWithFormat:@"当前账号:%@",[[UserDefaults objectForKey:@"user"] objectForKey:@"nickname"]];
    

}

- (void)getTheIndent{

    
    if ([UserDefaults objectForKey:@"user"]) {
        
        if (_wxPayButton.selected == YES) {
            
            
            [self sendPay_demoq ];
            
            
            return;
        }
        
        //支付宝
        else{
            /*
             *点击获取prodcut实例并初始化订单信息
             */
//            Product *product = [self.productList objectAtIndex:indexPath.row];
            
            /*
             *商户的唯一的parnter和seller。
             *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
             */
            
            /*============================================================================*/
            /*=======================需要填写商户app申请的===================================*/
            /*============================================================================*/
            NSString *partner = @"2088801965840135";
            NSString *seller = @"cnbizmedia@gmail.com";//cnbizmedia@gmail.com    shangjie@cnbizmedia.com
            NSString *privateKey = @"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMx7lWkdOTkAY5e0UX6912GnH8ioYEcS1raBli733syLlJZtVnXswFnAMS6GsDBAIULR1dsmDEkP3JDeAUoOg8GkgssXzY0Piqyl4fOWFphZFGGhMhH1nj8k5y2LaFOOtReLnYy19//MpRge0Ed/w1cdKW4F0LYCuokHgLVzbh6rAgMBAAECgYA8H+Jww9z9e7XM94I26A8acY+Q6qFUhJ+JjlTgfpWOQ0RvbrrLdc+hFDfh3EyWA2VERnrBM1DNctKB7iUm51mp4b8Nd3hvK6EgioFjSMfJqP6B0h0IAG9gXKiLTlvpRdJzwaTnHtfFPXMeRrIOeApLo0QIEutn37fj5mv+1iV8AQJBAPEtpS7mwHFZ/K/1BfrvyxBOi1oo3dBtFEzZl97FOuWBq0DRzdHU4NYFjsmehnfTsYAMQcuw1OJ987MHQjNSAQECQQDZDJ98eLZMZ4Zv2vF02an2bkdZrTevp9FG1ksbhfRDjGkuplNColYGvw1H57BDoNheLKv2Ra18YkOtRaYhNHOrAkBMRMgI9fYDopZzOoQin/RSetQ8tdG3mNcjmmgZjbubWo9Cl1aENdLIO8e04MnbWPm36ahg9tHLslL/2ZrIyfUBAkBkpAm/eWlt/ALGEssq11KLxY6n8j2D4ViUdADXfkFIoO6UhuLMXuFst2G9GZ0NfqNU53nE84IBzr56tXTWqK+JAkEA2EGSxMYDn4+HIX2JHQ9qHiM3C6taUKqto/DARbNAxIUd56+Ixg8N88Aq4SDRzZ66cbolbaeOIo8mfcXdqB8lyw==";
            /*============================================================================*/
            /*============================================================================*/
            /*============================================================================*/

            
            /*
             *生成订单信息及签名
             */
            //将商品信息赋予AlixPayOrder的成员变量
            Order *order = [[Order alloc] init];
            order.partner = partner;
            order.seller = seller;
            order.tradeNO = [goodsPayData objectForKey:@"order_sn"]; //订单ID（由商家自行制定）
            NSLog(@"[UserDefaults objectForKey:]  %@",goodsPayData);
            NSLog(@"order_sn    %@",[goodsPayData objectForKey:@"order_sn"]);
            order.productName =   _vipName.text; //商品标题
            order.productDescription = @"购买VIP"; //商品描述  购买VIP用户
//            NSLog(@"product.price %f",product.price);
//            product.price = 0.001f+pow(0.01,1);
//            product.price = 0.01f;
            //    0.001f+pow(0.01,1);
            
            NSString *moneyStr = [[NSString alloc] init];
            moneyStr = goodsPayData[@"total"] ;
//            @"0.01";//测试价格，1分钱
//
//            if ([[UserDefaults objectForKey:@"VIP"] isEqualToString:@"VIP"]) {
//                moneyStr = @"6000";
//            }
//            else{
//               moneyStr = @"20000";
//            }
            order.amount = [NSString stringWithFormat:@"%@",moneyStr]; //商品价格
            order.notifyURL = @"http://ksjv2.kanshangjie.com/library/alipay/shop_notify_url.php" ; //回调URL VIP @"http://ksjv2.kanshangjie.com/library/alipay/notify_url.php"
            
            order.service = @"mobile.securitypay.pay";
            order.paymentType = @"1";
            order.inputCharset = @"utf-8";
            order.itBPay = @"30m";
            order.showUrl = @"m.alipay.com";
            
            //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
            NSString *appScheme = @"alisdk";
            
            //将商品信息拼接成字符串
            NSString *orderSpec = [order description];
            NSLog(@"orderSpec = %@",orderSpec);
            
            //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
            id<DataSigner> signer = CreateRSADataSigner(privateKey);
            NSString *signedString = [signer signString:orderSpec];
            
            //将签名成功字符串格式化为订单字符串,请严格按照该格式
            NSString *orderString = nil;
            if (signedString != nil) {
                orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                               orderSpec, signedString, @"RSA"];
                
                //        orderString = [NSString stringWithFormat:@"%@&sign_type=\"%@\"",
                //                       orderSpec, @"RSA"];
                NSLog(@"orderString ==++ %@",orderString);
                
                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    
                 
                    
                    [self popOfDismss];
                    NSLog(@"reslut = %@",resultDic);
                }];
                
                //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
            
        }
     }
    
    }
}


-(void)popOfDismss{
    //发送一个更新VIP界面的通知
    
    //设置通知，刷新新的VIP的标示
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showTheNewVIP" object:self userInfo:nil ];
//    if ([[self.navigationController viewControllers] count]>=2) {
//        //        self.hidesBottomBarWhenPushed = NO;
//        [self.navigationController popViewControllerAnimated:YES];
//        
//    }else{
//        //    self.hidesBottomBarWhenPushed = NO;
//        [self dismissViewControllerAnimated:YES completion:nil];
//    }
    NSString *payEnd = [UserDefaults objectForKey: @"payEnd"];
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    NSLog(@"payEnd == %@",payEnd);
    if ([payEnd isEqualToString:@"yes"]) {
        PayOkViewController*login=[story instantiateViewControllerWithIdentifier:@"PayOkViewController"];
        UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:login];
//        [self presentViewController:nav animated:YES completion:nil];
        [self.navigationController pushViewController:login animated:YES];
    }
    else if([payEnd isEqualToString:@"no"]){
    
        PayBadViewController*login=[story instantiateViewControllerWithIdentifier:@"PayBadViewController"];
        UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:login];
//        [self presentViewController:nav animated:YES completion:nil];
        [self.navigationController pushViewController:login animated:YES];
    }
    
    
}

//微信支付
- (void)sendPay_demoq
{
    //{{{
    //本实例只是演示签名过程， 请将该过程在商户服务器上实现
    
    //创建支付签名对象
    payRequsestHandler *req = [payRequsestHandler alloc];
    //初始化支付签名对象
    [req init:APP_ID mch_id:MCH_ID];
    //设置密钥
    [req setKey:PARTNER_ID];
    
    //}}}
    NSLog(@"req === %@",req);
    //获取到实际调起微信支付的参数后，在app端调起支付
    
    NSLog(@"req sendPay_demo == %@",[req sendPay_demo]);
    NSDictionary *dic = [req sendPay_demo];
    NSLog(@"dic == %@",dic);
    NSMutableDictionary *dict =   [NSMutableDictionary dictionaryWithDictionary:[req sendPay_demo]];
    NSLog(@"dict == %@",dict);
    
    if(dict == nil){
        //错误提示
        NSString *debug = [req getDebugifo];
        
        [self alert:@"提示信息" msg:debug];
        
        NSLog(@"%@\n\n",debug);
    }else{
        NSLog(@"%@\n\n",[req getDebugifo]);
        //[self alert:@"确认" msg:@"下单成功，点击OK后调起支付！"];
        
        NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
        
        //判断是微信支付还是微信登陆
        [UserDefaults setObject:@"wxpay" forKey:@"wx"];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [dict objectForKey:@"appid"];
        req.partnerId           = [dict objectForKey:@"partnerid"];
        req.prepayId            = [dict objectForKey:@"prepayid"];
        req.nonceStr            = [dict objectForKey:@"noncestr"];
        req.timeStamp           = stamp.intValue;
        req.package             = [dict objectForKey:@"package"];
        req.sign                = [dict objectForKey:@"sign"];
        
        [WXApi sendReq:req];
    }
}


 


//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
    
}

    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



- (IBAction)wxPay:(id)sender {
    
    _wxPayButton.selected=YES;

    _zfbPayButton.selected=NO;
  
}


- (IBAction)zfbPay:(id)sender {
    
    _wxPayButton.selected=NO;
    
    _zfbPayButton.selected=YES;
    
}


- (IBAction)goToPayMoney:(id)sender {
    
//    if ([[UserDefaults objectForKey:@"trial"] integerValue] == 2) {
//        [self getTheIndent];//去支付
//    }
//    else{
//    
//    [SVProgressHUD showSuccessWithStatus:@"正在审核，请稍后在试。"];
//    }
    
    [self getTheIndent];//去支付
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
